package serialport;

import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import beans.ScmSerialPortBean;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import singleton.SingletonClass;
import utils.ActivityUtil;
import utils.CRCUtils;
import utils.DigitalTrans;
import utils.TimeUtil;
import utils.ToastUtil;

/**
 * Created by Administrator on 2018/5/18.
 */

public class SendMessToScm {

    private MyHandler allHandler;
    public SharedPreferences sharedPreferences;
    private ScmSerialPortBean bean;
    private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    private boolean isRoll;
    private int count;

    public SendMessToScm(ScmSerialPortBean bean) {
        this.bean = bean;
        allHandler = SingletonClass.getSingleton(MyHandler.class);
        sharedPreferences = ActivityUtil.getSharedPreferences(bean.getmContext());
    }

    public void onHandleMessage(Message msg) {
        //执行到此处,说明发送之后一定时间内,没有收到接收方的应答帧,进行重发,重发的次数为3
        switch (msg.what) {
            //向单片机重新发送
            case HandlerConstant.SERIAL_PORT_REPEAT:
                if (bean.getCount() < Constants.REPEAT_COUNT) {
                    bean.setCount(bean.getCount() + 1);
                    writeData(bean.getSerialPortString(), true);
                } else {
                    //进行设备出现故障的相关提示,并且应该解锁按钮
//                    allHandler.sendEmptyMessage(HandlerConstant.UNLOCK_CLICK);
                    ToastUtil.showToast(bean.getmContext(), "通信失败,请检查设备");
                    bean.setCount(0);
                }
                break;
            case HandlerConstant.TAKE_OUT:
//            case HandlerConstant.RETURN:
            case HandlerConstant.CHECK:
            case HandlerConstant.CHECK_AGAIN:
                Log.e("BBB", "010000" + (int) msg.obj);
                bean.setSelectCabinet((int) msg.obj);
                writeData("010000", true);
//                allHandler.sendEmptyMessage(HandlerConstant.OPEN_DOOR);
                break;
            case HandlerConstant.BEGIN_INVENTORY:
                Log.e("CCC", "BEGIN_INVENTORY: " );
                bean.setSelectCabinet((int) msg.obj);
                //盘点,要注意重发的时间
                writeData("090000", true);
                break;
            case HandlerConstant.SET_RFID:
                String s = (String) msg.obj;
                writeData("060008" + s, true);
                break;
            case HandlerConstant.FLASH_ON:
                bean.setSelectCabinet((int) msg.obj);
                writeData("07000101", true);
                break;
            case HandlerConstant.FLASH_OFF:
                bean.setSelectCabinet((int) msg.obj);
                writeData("07000100", true);
                break;
            case HandlerConstant.BEGIN_SCM_NUMBER:
                bean.setSelectCabinet((int) msg.obj);
                bean.setCabinetCode(true);
                break;
            case HandlerConstant.NO_BEGIN_SCM_NUMBER:
                bean.setCabinetCode(false);
                break;
            case HandlerConstant.ROLL:
                roll(msg);
                break;
            case HandlerConstant.GET_CABINET_SET:
                bean.setSelectCabinet((int) msg.obj);
                writeData("050000", true);
                break;
            case 123456:
                try {
                    bean.getmOutputStream().write(DigitalTrans.hexStringToByteArray("584C4B4A010101" + "FFFFFFFFFFFF" + Constants.ANDROID_ADDRESS + "06000EFFFFFFFFFFFFFFFF"+"012233445566" + "ffff" ) );
                    Log.e("AAA","584C4B4A010101" + "FFFFFFFFFFFF1234567890AB" + "06000EFFFFFFFFFFFFFFFF"+"012233445566" + "ffff"   );
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
    private int role;
    //轮询
    private void roll(Message msg) {

        if (++count <=3){
            //轮询
            allHandler.sendEmptyMessageDelayed(HandlerConstant.ROLL,3000);
        }

        int roleId;
        if (!isRoll) {
            roleId = (int) msg.obj;
            role = (int) msg.obj;
        }else {
            roleId = role;
        }

        if (roleId != 4) {
            //医院的权限,轮询所有柜子
            for (int i = 1; i < 6; i++) {
//                    address1 = sharedPreferences.getString("Address" + i, "");
//                    if (!TextUtils.isEmpty(address1)) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                bean.setSelectCabinet(i);
                writeData("0A0000", false);
//                    }
            }
        } else {
            //医药厂商的权限,轮询权限允许的柜子
            String[] split = sharedPreferences.getString(Constants.ENABLE_LOGICNUMBER, "").split(",");
            for (int i = 0; i < split.length; i++) {
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                bean.setSelectCabinet(Integer.valueOf(split[i]));
                writeData("0A0000", false);
            }
        }

        isRoll = true;
    }

    //hexString从命令类型开始写
    public void writeData(String hexString, boolean isRepeat) {

        try {
            bean.setPackageCount(0);
            String address1 = sharedPreferences.getString(Constants.ADDRESS + bean.getSelectCabinet(), "");
            if (!TextUtils.isEmpty(address1)) {
                bean.setSerialPortString(hexString);
                String s = "010101" + address1 + Constants.ANDROID_ADDRESS + hexString ;
                Log.e("AAA", "writeData: " + s );
                byte[] bytes = DigitalTrans.hexStringToByteArray(s);
                char crc = CRCUtils.getCrc(bytes, (byte) bytes.length);
                int i = (int)crc;

                String check =  DigitalTrans.hexNumberFormat(i,4);

//                saveToFile(address1 + Constants.ANDROID_ADDRESS + "    " + hexString  + "    "  + check );
//                bean.getmOutputStream().write(DigitalTrans.hexStringToByteArray("584C4B4A010101" + address1 + Constants.ANDROID_ADDRESS + hexString + check));

                saveToFile(address1 + Constants.ANDROID_ADDRESS + "    " + hexString  );
                bean.getmOutputStream().write(DigitalTrans.hexStringToByteArray("584C4B4A010101" + address1 + Constants.ANDROID_ADDRESS + hexString ));

                if (isRepeat) {
                    sendEmptyMessageDelayed(HandlerConstant.SERIAL_PORT_REPEAT, Constants.REPART_DELAY);
                }
            }

        } catch (IOException e) {
            saveToFile(e.getMessage() );
            e.printStackTrace();
        }
    }

    void sendEmptyMessageDelayed(int what, long delayMillis) {
        bean.getSerialPortData().sendEmptyFrameMessageDelayed(what, delayMillis);
    }

    public void saveToFile(String receiveData) {
        StringBuffer sb = new StringBuffer();
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                String time = formatter.format(new Date());
                sb.append(time);
                sb.append("  --send begin--:  ");
                sb.append(receiveData);
                sb.append("  --send end--;  ");
                sb.append("\r\n");
                String fileName =TimeUtil.getYear()+"-"+(TimeUtil.getMonth()+1)+"-"+ TimeUtil.getDay()+".log";
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/serialport/";
                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(path + fileName, true);
                fos.write(sb.toString().getBytes());
                fos.flush();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
